package com.xyz.mqtt;

import com.xyz.entity.mapper.SystemMqttLogMapper;
import com.xyz.entity.pojo.SystemMqttLog;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * MQTT发送客户端的回调类
 */
@Component
public class MqttSendCallBack implements MqttCallbackExtended {

    private static final Logger logger = LoggerFactory.getLogger(MqttSendCallBack.class);

    @Autowired
    private MqttSendClient mqttSendClient;

    @Autowired
    private MqttConfig mqtt;

    @Autowired
    private SystemMqttLogMapper systemMqttLogMapper;

    /**
     * 客户端断开后触发
     */
    @Override
    public void connectionLost(Throwable throwable) {
        logger.warn("连接断开，可以重连");
        if (MqttSendClient.client == null || !MqttSendClient.client.isConnected()) {
            logger.warn("【重新连接】....................................................");
            mqttSendClient.reconnection();
        }
    }

    /**
     * 客户端收到消息触发
     *
     * @param topic       主题
     * @param mqttMessage 消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        logger.warn("【接收消息主题】: " + topic);
        logger.warn("【接收消息Qos】: " + mqttMessage.getQos());
        logger.warn("【接收消息内容】: " + new String(mqttMessage.getPayload(), StandardCharsets.UTF_8));
        SystemMqttLog newSml = new SystemMqttLog();
        newSml.setTopic(topic);
        newSml.setQos(mqttMessage.getQos());
        newSml.setContent(new String(mqttMessage.getPayload()));
        newSml.setTime(new Date());
        systemMqttLogMapper.insert(newSml);
    }

    /**
     * 发布消息成功
     *
     * @param token token
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        try {
            String topic = token.getTopics()[0];
            MqttMessage message = token.getMessage();
            byte[] payload = message.getPayload();
            String s = new String(payload, StandardCharsets.UTF_8);

            logger.warn("【发送消息主题】: " + topic);
            logger.warn("【发送消息Qos】: " + message.getQos());
            logger.warn("【发送消息内容】: " + s);

            SystemMqttLog newSml = new SystemMqttLog();
            newSml.setTopic(topic);
            newSml.setQos(message.getQos());
            newSml.setContent(s);
            newSml.setTime(new Date());
            systemMqttLogMapper.insert(newSml);

        } catch (Exception e) {
            logger.warn("MqttSendCallBack deliveryComplete error,message:{}", e.getMessage());
        }
    }

    /**
     * 连接emq服务器后触发
     */
    @Override
    public void connectComplete(boolean b, String s) {
        logger.warn("============================= 客户端【" + MqttSendClient.client.getClientId() + "】连接成功！=============================");
        // 订阅所有机构主题
        mqttSendClient.subscribe(mqtt.getSubscribeTopicAlarm(), 0);
        mqttSendClient.subscribe(mqtt.getSubscribeTopicRuntimeRunningTime(), 0);
        mqttSendClient.subscribe(mqtt.getSubscribeTopicRuntimeDeviceStatus(), 0);
    }
}
